<?php
class SalesController extends AppController {

	var $name = 'Sales';
	var $helpers = array('Html', 'Form', 'Ajax', 'Javascript', 'timediff');
	var $uses = array('Sale', 'Follow','Category', 'Bidagent', 'User');


	function beforeFilter() {
		parent::beforeFilter();

		if(!$this->Admin)
		{
			$this->Auth->allow('index','index_closed', 'view','licitate','follow','unfollow');
		}
		else
		{
			$this->Auth->allow('*');
		}
	}







	function index($category_id = null) {
		$this->pageTitle = 'View auctions';
		$this->Sale->recursive = 2;
		if($category_id=='home' || $category_id==null)
		$conditions = array("Sale.timeEnd >=" => date('Y-m-d  H:i:s', +strtotime("-5 minutes", $_SERVER['REQUEST_TIME'])));
		else
		$conditions = array("Sale.timeEnd >=" => date('Y-m-d  H:i:s', +strtotime("-5 minutes", $_SERVER['REQUEST_TIME'])),
								"Item.category_id"=>$category_id);
			
			
		$this->paginate =  array('limit'=> 18, 'order' => 'Sale.originalTimeEnd ASC');
		$lang = $this->Session->read('Config.language');
		$this->currencyLoad($lang);

		$categories = $this->Category->find('list');
		$this->set('sales', $this->paginate($conditions));

		$this->set(compact('categories'));

	}



	function index_closed($category_id=null) {

		$this->pageTitle = 'View closed auctions';
		$this->Sale->recursive = 2;

		if($category_id==null)
			$conditions = array("Sale.timeEnd <" => date('Y-m-d  H:i:s', $_SERVER['REQUEST_TIME']));
		else
			$conditions = array("Sale.timeEnd <" => date('Y-m-d  H:i:s', $_SERVER['REQUEST_TIME']),
								"Item.category_id"=>$category_id);
			
		$this->paginate =  array('limit'=> 18, 'order' => 'Sale.timeEnd DESC');
		$lang = $this->Session->read('Config.language');
		$this->currencyLoad($lang);
		$this->set('sales', $this->paginate($conditions));

	}

	function follow($id = null) {
		if (!$this->Auth->user('id')) {
			$this->Session->setFlash(__('Please login', true));
			$this->redirect(array('controller' => 'users','action'=>'login'));
		}
		App::import('model','Follow');
		$follow = new Follow();

		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Sale', true));
			$this->redirect(array('action'=>'index'));
		}

		if ($follow->save(array('sale_id'=>$id,
								'user_id' => $this->Auth->user('id'))))
		{
			$this->Session->setFlash(__('Following ', true));

		}
		$this->redirect(array('controller' => 'sales','action'=>'view',$id));

	}



	function unfollow($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Sale', true));
			$this->redirect(array('action'=>'index'));
		}

		$result = $this->Follow->find('first',array('conditions'=>array('Follow.user_id'=>$this->Auth->user('id'), 'Follow.sale_id'=>$id)));
		if ($this->Follow->delete($result['Follow']['id']) )
		{
			$this->Session->setFlash(__('Unfollowed ', true));
			$this->redirect(array('controller' => 'sales','action'=>'view',$id));
		}
		$this->Session->setFlash(__('FAIL! ', true));
		$this->redirect(array('controller' => 'sales','action'=>'view',$id));


	}

	function licitate($id = null, $page=null, $params=null) {
		App::import('model','Licitation');
		$licitation = new Licitation();

		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Sale', true));
			$this->redirect(array('action'=>'index'));
		}

		if (!$this->Auth->user('id')) {
			$this->Session->setFlash(__('Please login', true));
			$this->redirect(array('controller' => 'users','action'=>'login'));
		}

		if ($this->Auth->user('nrLicitations')==0)
		{
			$this->Session->setFlash(__('Insufficient licitations', true));
			$this->redirect(array('action'=>'index'));
		}

		$this->data = $this->Sale->read(null, $id);

		$price = $this->data['Sale']['currentPrice'] + 0.01;
		$timeEnd = date('Y-m-d H:i:s', +strtotime("+15 seconds",strtotime($this->data['Sale']['timeEnd'])));
		$licitationTime = $_SERVER['REQUEST_TIME'];

		if(strtotime($this->data['Sale']['timeEnd']) < $licitationTime)
		{
			$this->Session->setFlash(__('Auction already over', true));
			$this->redirect(array('action'=>'index'));
		}

		App::import('Model', 'User');
		$user = new User();
		$user->id = $this->Auth->user('id');

		$ourUser= $user->read(null, $this->Auth->user('id'));
		
		if ($this->Sale->save(array('user_id' => $this->Auth->user('id'), 'currentPrice' => $price,
			 'timeEnd' => $timeEnd, false)) 
		&&
		$licitation->save(array('user_id' => $this->Auth->user('id'),
			 'timeLicitation'=>date('Y-m-d H:i:s',$licitationTime),
			 'price'=>$price,
			 'sale_id'=>$this->data['Sale']['id']))
		&&
		$user->saveField('nrLicitations', $ourUser['User']['nrLicitations'] - 1))
		{
			$this->Session->write('Auth.User.nrLicitations',$ourUser['User']['nrLicitations'] - 1);
			$this->redirect(array('action'=>$page,$params));

		}
			

	}


	function view($id = null) {

		// Validar se id é valido
		if (!$id) {
			$this->Session->setFlash(__('Invalid Sale.', true));
			$this->redirect(array('action'=>'index'));
		}
		
		// Ler sale
		$this->Sale->recursive = 2;
		$this->Sale = $this->Sale->read(null, $id);
		$this->set('sale', $this->Sale);

		// Obter licitações para esta sale
		App::import('model','Licitation');
		$licitation = new Licitation();		
		$conditions = array('Licitation.sale_id'=>$id);
		$this->set('licitations', $licitation->find('all',array('conditions' => $conditions,'limit'=>10, 'order' =>'Licitation.timeLicitation DESC')));

		// Ler qual a linguagem e invocar função que irá determinar valor de conversão de moeda
		$lang = $this->Session->read('Config.language');
		$this->currencyLoad($lang);

		// Verificar se utilizador loggado está a seguir esta sale
		App::import('model','Follow');
		$follow = new Follow();
		if($follow->find('first', array('conditions' => array('Follow.user_id'=>$this->Auth->user('id'), 'Follow.sale_id'=>$id))))
		{
			$this->set('isFollowing',true);
		} else
		{
			$this->set('isFollowing',false);
		}

		// Verificar se utilizador loggado tem um bidagent para este sale
		App::import('model','Bidagent');
		$bidagent = new Bidagent();
		if($bidagent->find('first', array('conditions' => array('Bidagent.user_id'=>$this->Auth->user('id'), 'Bidagent.sale_id'=>$id))))
		{
			$this->set('hasAgent',true);
			$this->set('agent', $bidagent->find('first', array('conditions' => array('Bidagent.user_id'=>$this->Auth->user('id'), 'Bidagent.sale_id'=>$id))));
		} else
		{
			$this->set('hasAgent',false);
		}
		
		// Se sale estiver terminada calcular quanto gastou o utilizador nesta sale
		if(strtotime($this->Sale['Sale']['timeEnd']) < $_SERVER['REQUEST_TIME'])
		{
			// Select count de licitations deste utilizador
			$conditions = array('Licitation.user_id'=>$this->Sale['User']['id'], 'Licitation.sale_id'=>$this->Sale['Sale']['id']);	
			$nLicitations = $licitation->find('count',array('conditions' => $conditions));
			$this->set('nLicitations', $nLicitations);
			$this->set('totalPrice', ($nLicitations * 0.25)+$this->Sale['Sale']['currentPrice']);
		}
		
		
		
		

	}

	function add() {
		if (!empty($this->data)) {
			$this->Sale->create();
			if ($this->Sale->save($this->data)) {
				$this->Session->setFlash(__('The Sale has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Sale could not be saved. Please, try again.', true));
			}
		}
		$items = $this->Sale->Item->find('list');
		$users = $this->Sale->User->find('list');
		$this->set(compact('items', 'users'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Sale', true));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->Sale->save($this->data)) {
				$this->Session->setFlash(__('The Sale has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Sale could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Sale->read(null, $id);
		}
		$items = $this->Sale->Item->find('list');
		$users = $this->Sale->User->find('list');
		$this->set(compact('items','users'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Sale', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Sale->del($id)) {
			$this->Session->setFlash(__('Sale deleted', true));
			$this->redirect(array('action'=>'index'));
		}
	}


	function admin_index() {
		$this->Sale->recursive = 0;
		$this->set('sales', $this->paginate());
	}


}
?>